package com.eipv.multidatasource.component.config.datasource;

import com.eipv.multidatasource.component.interceptor.MybatisSqlInterceptor;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan(basePackages = MysqlDataSourceConfigBean.MAPPER_PACKAGE, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataSourceConfigBean extends AbstractDataSourceConfigBean {

    /**
     * 精确到 master 目录，以便跟其他数据源隔离
     */
    static final String ENTITY_PACKAGE = "com.eipv.multidatasource.entity";
    static final String MAPPER_PACKAGE = "com.eipv.multidatasource.mapper.mysql";
    static final String MAPPER_LOCATION = "classpath:mybatis/mysql/mapper/*.xml";

    @Autowired
    private MysqlDataSourceConfig mysqlDataSourceConfig;
    @Autowired(required = false)
    private MybatisSqlInterceptor mybatisSqlInterceptor;

    @Bean(name = "mysqlDataSource")
    @Primary
    @Override
    public DataSource dataSource() {
        return super.dataSource();
    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    @Override
    public DataSourceTransactionManager transactionManager() {
        return super.transactionManager();
    }

    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    @Override
    public SqlSessionFactory sqlSessionFactory()
            throws Exception {
        return super.sqlSessionFactory();
    }

    @Override
    protected DataSourceConfig getDataSourceConfig() {
        return mysqlDataSourceConfig;
    }

    @Override
    protected String getEntityPackage() {
        return ENTITY_PACKAGE;
    }

    @Override
    protected String getMapperLocation() {
        return MAPPER_LOCATION;
    }

    @Override
    protected Interceptor[] getInterceptors() {
        //分页插件
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        interceptor.setProperties(properties);
        if(mybatisSqlInterceptor==null) {
            return new Interceptor[]{interceptor};
        }
        return new Interceptor[]{interceptor,mybatisSqlInterceptor};
    }
}
